package com.itheima.springbootwebtlias.aspect;

import com.itheima.springbootwebtlias.common.CurrentHolder;
import com.itheima.springbootwebtlias.mapper.OperateLogMapper;
import com.itheima.springbootwebtlias.pojo.OperateLog;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 记录操作日志的切面类
 */
@Slf4j
@Component
//@Aspect
public class OperationLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Autowired
    private HttpServletRequest request;

    // 切入点表达式：execution+annotation
    @Around("execution(void com.itheima.springbootwebtlias.service.*Service.*(..)) && @annotation(com.itheima.springbootwebtlias.annotation.LogOperation)")
    // 通知类型：环绕通知
    public Object recordOperationLog(ProceedingJoinPoint pjp) throws Throwable{
        // 记录操作日志：收集操作日志信息，添加到操作日志数据表中
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();
        long costTime = end - start;

        // 1.定义操作日志对象，收集操作日志信息
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateTime(LocalDateTime.now()); //操作时间
        operateLog.setReturnValue(result+""); // 返回值
        operateLog.setCostTime(costTime); // 执行耗时

        operateLog.setClassName(pjp.getSignature().getDeclaringType().getName()); // 获取目标方法所属的类名
        operateLog.setMethodName(pjp.getSignature().getName());  // 获取目标方法名称
        operateLog.setMethodParams(Arrays.toString(pjp.getArgs())); // 获取目标方法参数
        operateLog.setOperateEmpId(CurrentHolder.getCurrentId()); // 操作员工id

        // 2.调用操作日志的持久层接口，添加日志信息到操作日志表中
        operateLogMapper.insert(operateLog);

        return result;
    }
}
